import React, { useEffect, useState } from 'react'
import { ReactHashCalendar } from 'react-hash-calendar'
import style from './calendar.modules.css'
import { searchUserProjectList } from './api'
import Card from './card'
import formatDate from '../../utils/formatDate'

export default function Calendar() {
  const [userProject, setUserProject] = useState([])
  const [userDayProject, setUserDayProject] = useState([])
  const [flag, setFlag] = useState(1)

  const userId = JSON.parse(localStorage.getItem('token')).id || ''
  const getUserProject = async () => {
    await searchUserProjectList(userId).then(res => {
      setUserProject(res.data)
    })
  }
  const getRandom = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min
  }
  const getDayUser = date => {
    const arr = []
    setUserDayProject(arr)
    userProject.map(ele => {
      if (ele.project.date === date) {
        arr.push(ele.project)
        setUserDayProject(arr)
      }
    })
  }
  useEffect(() => {
    let timer = setTimeout(() => {
      setFlag(2)
    }, 50)
    getUserProject()
    getDayUser(formatDate(new Date()))
    return (timer = null)
  }, [flag])
  return (
    <div className="content">
      <ReactHashCalendar
        model="inline"
        markType="dot+circle"
        // markDate={[
        //   { color: 'red', date: ['2022/04/25'] },
        //   { color: 'red', date: ['2022/04/20'] },
        // ]}
        format="YY-MM-DD"
        dateClickCallback={date => {
          getDayUser(date)
        }}
      />

      <section>
        {userDayProject.length === 0 ? (
          <p
            style={{
              marginTop: '12px',
            }}
          >
            您今日没有预约
          </p>
        ) : (
          userDayProject.map(item => (
            <Card
              title={item.title}
              imgUrl={item.imgUrl}
              time={item.time}
              key={getRandom(0, 99999)}
            />
          ))
        )}
      </section>
    </div>
  )
}
